from common.BaseHandler import BaseHandler
from common.Models import Post, Visitor, Comment


class CommentHandler(BaseHandler):
    def get(self):
        result = self.result()
        data = self.get_params()
        try:
            post_id = self.data_null(data, "post_id", "请选择文章！")
            comments = self.session.query(Comment.content, Comment.create_time, Visitor.nick_name)\
                            .filter_by(post_id=int(post_id), is_delete=0)\
                            .join(Visitor, Visitor.id == Comment.visitor_id)\
                            .order_by(Comment.create_time.desc())\
                            .all()
            for c in comments:
                print(c)

            result["status"] = 1
            result["msg"] = "数据获取成功！"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, "数据获取失败！")
        self.write(result)

    def post(self):
        result = self.result()
        data = self.get_body()
        try:
            post_id = self.data_null(data, "post_id", "请选择评论的文章！")
            nick_name = self.data_null(data, "nick_name", "请输入昵称！")
            email = self.data_null(data, "email", "请输入邮箱！")
            content = self.data_null(data, "content", "请输入内容！")
            post_obj = self.session.query(Post).filter_by(id=int(post_id), is_delete=0).first()
            if not post_obj:
                self.data_except("请确认博文是否存在！")
            visitor_obj = self.session.query(Visitor).filter_by(nick_name=nick_name, email=email, is_delete=0).first()
            if not visitor_obj:
                visitor_obj = Visitor(nick_name=nick_name, email=email)
                self.session.add(visitor_obj)
                self.session.commit()
            new_comment = Comment(visitor_id=visitor_obj.id, post_id=post_obj.id, content=content)
            self.session.add(new_comment)
            self.session.commit()
            result["status"] = 1
            result["msg"] = "评论成功！"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e, "评论失败！")
        self.write(result)



